/*
* author : douyu
* date : 2024/1/5 09:49
* description : source_change_notifier
*/

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_android_tv/Routes/Model/source_category_model.dart';
import 'package:flutter_android_tv/Routes/download_source.dart';
import 'package:flutter_android_tv/Routes/Event/event_bus_type.dart';
import 'package:flutter_android_tv/common_tool/zjLogFile.dart';
import '../Model/source_info_model.dart';
import '../Tools/keyboard_code.dart';


class IPTVSecondarySourceProvider extends ChangeNotifier {
  late SourceCategoryModel _categoryModel ;

  SourceCategoryModel get categoryModel => _categoryModel;

  IPTVSecondarySourceProvider(){
    _categoryModel = SourceCategoryModel(name: "等待", sources: []);
    //监听数据变化
    eventBus.on<ChangeSecondarySourceEvent>().listen((event) {
      //数据变化,数据处理
      if(event.categoryModel.sources.isNotEmpty){
        /// 不是同一个分类才会进行刷新
        changeCategory(event.categoryModel,shouldPlay: event.isShouldPlay);
      }
    });
  }

  /// 首次更新数据
  void changeCategory(SourceCategoryModel categoryModel,{bool shouldPlay = false}){
    _categoryModel = categoryModel;
    if(shouldPlay){
      //通知刷新界面,播放第一个数据源
      eventBus.fire(ChangePlaySourceEvent(_categoryModel.sources.first));
    }
    zjLog("切换数据111111======");
    notifyListeners();
  }

  /// 选中更新展示数据，上下键进行切换展示数据
  void selectIPTVSourceWithIndex(int index){
    _categoryModel.sources = _categoryModel.sources.map((e) => e.isChoose = false).cast<SourceInfoModel>().toList();
    _categoryModel.sources[index].isChoose = true;

    notifyListeners();
  }
}

class IPTVCategoryProvider extends ChangeNotifier {
  /// 播放数据源
  late List<SourceCategoryModel> _categorySources = [];
  /// 设置获取的get方法
  List<SourceCategoryModel> get categorySources => _categorySources;
  /// 当前选中的播放源
  int _categoryIndex = 0;
  int get categoryIndex => _categoryIndex;
  /// 当前选中的播放源
  int _secondaryIndex = 0;
  int get secondaryIndex => _secondaryIndex;
  /// 选中的资源的播放源
  int _currentSourceIndex = 0;
  /// 是否在切换播放源
  bool _isChangingSource = false;
  /// 是否选中了第一个
  bool _isChooseCategory = false;

  /// 侧边栏中选中的结果
  int _slideChooseIndex = 0;

  /// 侧边栏是否隐藏
  bool _isShowSlide = false;

  late SourceCategoryModel _currentCategoryModel;

  IPTVCategoryProvider(){
    /// 初始化执行 拉取数据源展示数据
    _loadSourceFile();
    _initSourceData();
  }

  /// 加载本地和网络资源
  void _initSourceData() async{
    String source = (await ZJDownloadSource.downloadSource()) ?? "";
    if(source.isNotEmpty){
      _dealLiveSource(source);
    }
  }

  /// 处理本地数据展示问题
  void _loadSourceFile() async {
    String jsonContent = await rootBundle.loadString("assets/resources/live_source.json");
    _dealLiveSource(jsonContent);
  }

  /// 处理json数据
  void _dealLiveSource(String jsonStr) {
    //使用网络数据
    _categorySources.clear();
    Map<String,dynamic> sourcesList = json.decode(jsonStr);
    for (var entry in sourcesList.entries){
      List<SourceInfoModel> sourceList = [];
      for(var data in entry.value){
        var model = SourceInfoModel.fromJson(data);
        if(model.sources.isNotEmpty){
          sourceList.add(model);
        }
      }
      if(sourceList.isNotEmpty){
        var category = SourceCategoryModel(name: entry.key, sources: sourceList);
        _categorySources.add(category);
      }
    }
    /// 获取到数据开始播放
    _currentCategoryModel =  _categorySources[_categoryIndex];
    _currentCategoryModel.isChoose = true;
    _currentCategoryModel.sources[_secondaryIndex].isChoose = true;
    eventBus.fire(ChangeSecondarySourceEvent(_currentCategoryModel,shouldPlay: true));

    notifyListeners();
  }

  ///监听键盘点击回调
  void keyBoardPressListener(int keyCode){
    // /// 点击返回键
    // if(keyCode == KeyBoardCode.KEYCODE_BACK){
    //   /// 侧边栏展示 隐藏侧边栏
    //   if(_isShowSlide){
    //     _isShowSlide = !_isShowSlide;
    //     eventBus.fire(SlideShowChangeEvent(_isShowSlide));
    //   }else{
    //     /// 退出弹窗
    //     eventBus.fire(ShowQuitDialogEvent());
    //   }
    //   return;
    // }

    //点击确认按钮
    if(keyCode == KeyBoardCode.KEYCODE_DPAD_CENTER){
      _isChangingSource = false;
      if(_isShowSlide){
        //上下切换之后选中当前的元数据 进行播放
        _secondaryIndex = _slideChooseIndex;
        _currentSourceIndex = 0;
        _currentCategoryModel =  _categorySources[_categoryIndex];
        SourceInfoModel infoModel = _currentCategoryModel.sources[_secondaryIndex];
        //开始播放
        eventBus.fire(ChangePlaySourceEvent(infoModel));
      }
      //重新计算位置信息
      int categoryIndex = _categorySources.indexWhere((element) => element.name == _currentCategoryModel.name);
      if(categoryIndex != -1){
        _categoryIndex = categoryIndex;
      }

      _isShowSlide = !_isShowSlide;
      //定位当前正在播放的内容
      _slideChooseIndex = _secondaryIndex;
      /// 隐藏或展示侧边栏
      eventBus.fire(SlideShowChangeEvent(_isShowSlide));
      /// 设置slide选中的index  并滚动到当前位置
      eventBus.fire(SlideChangeWithIndexEvent(_categoryIndex,_secondaryIndex));

      return;
    }

    /// 播放列表未出现时 左右切换播放源操作
    if(!_isShowSlide && (keyCode == KeyBoardCode.KEYCODE_DPAD_LEFT || keyCode == KeyBoardCode.KEYCODE_DPAD_RIGHT)){
      //切换播放源
      _isChangingSource = true;
      SourceCategoryModel categoryModel =  _categorySources[_categoryIndex];
      SourceInfoModel model =  categoryModel.sources[_secondaryIndex];
      int maxLength = model.sources.length;
      if(keyCode == KeyBoardCode.KEYCODE_DPAD_LEFT){
        _currentSourceIndex -= 1;
      }else{
        _currentSourceIndex += 1;
      }
      if(_currentSourceIndex < 0){
        _currentSourceIndex = maxLength - 1;
      }else if(_currentSourceIndex > maxLength){
        _currentSourceIndex = 0;
      }
      //开始播放
      eventBus.fire(ChangePlaySourceEvent(model,index: _currentSourceIndex));
      return;
    }

    /// 播放列表出现时，左右两个菜单 互动
    if(keyCode == KeyBoardCode.KEYCODE_DPAD_LEFT || keyCode == KeyBoardCode.KEYCODE_DPAD_RIGHT){
      _changeCategoryStatus(keyCode);
      return;
    }

    ///上下切换频道操作
    if(keyCode != KeyBoardCode.KEYCODE_DPAD_UP && keyCode != KeyBoardCode.KEYCODE_DPAD_DOWN){
      return;
    }
    /// 计算展示的位置信息
    SourceCategoryModel currentModel = _categorySources[_categoryIndex];
    int temCurrentIndex = _slideChooseIndex;
    zjLog("当前选中的值=======111111,index:$temCurrentIndex");
    if(_isShowSlide){
      if(_isChooseCategory){
        temCurrentIndex = _categoryIndex;
        zjLog("当前选中的值=======222222,index:$temCurrentIndex");
      }else{
        //在当前数据源中进行选择
        if(_currentCategoryModel.name == currentModel.name){
          temCurrentIndex = _secondaryIndex;
        }
        zjLog("当前选中的值=======333333,index:$temCurrentIndex");
      }
    }
    zjLog("当前选中的值=======444444,index:$temCurrentIndex");
    if(keyCode == KeyBoardCode.KEYCODE_DPAD_UP){
      temCurrentIndex -= 1;
    }else if(keyCode == KeyBoardCode.KEYCODE_DPAD_DOWN){
      temCurrentIndex += 1;
    }
    //比较当前展示的值

    var maxCount = _isChooseCategory ? _categorySources.length : currentModel.sources.length;

    if(temCurrentIndex < 0){
      temCurrentIndex = maxCount - 1;
    }else if(temCurrentIndex >= maxCount){
      temCurrentIndex = 0;
    }
    zjLog("当前选中的值=======555555,index:$temCurrentIndex");


    if(_isShowSlide){
      if(_isChooseCategory){
        /// 重置选中一个新的category _secondaryIndex
        _categoryIndex = temCurrentIndex;
        SourceCategoryModel tempModel = _categorySources[_categoryIndex];
        if(_currentCategoryModel.name != tempModel.name){
          _slideChooseIndex = 0;
          temCurrentIndex = 0;
          zjLog("当前选中的值=======666666,index:$temCurrentIndex");
        }
      }else{
        SourceCategoryModel tempModel = _categorySources[_categoryIndex];
        if(_currentCategoryModel.name != tempModel.name){
          _slideChooseIndex = temCurrentIndex;
          zjLog("当前选中的值=======777777,index:$temCurrentIndex");
        }else{
          _secondaryIndex = temCurrentIndex;
          zjLog("当前选中的值=======888888,index:$temCurrentIndex");
        }
      }
      zjLog("当前选中的值=======999999,index:$temCurrentIndex");
      _changeSlideSelected(_categoryIndex, temCurrentIndex);
      eventBus.fire(SlideChangeWithIndexEvent(_categoryIndex, temCurrentIndex));
      //通知刷新UI
      notifyListeners();
      return;
    }

    /// 侧边栏没有展示时 修改选中播放源,只在一个category中进行循环切换
    _secondaryIndex = temCurrentIndex;
    _slideChooseIndex = temCurrentIndex;
    _changeSlideSelected(_categoryIndex, _secondaryIndex);
    eventBus.fire(SlideChangeWithIndexEvent(_categoryIndex, _secondaryIndex));

    _currentSourceIndex = 0;
    _isChangingSource = false;
    SourceCategoryModel categoryModel =  _categorySources[_categoryIndex];
    SourceInfoModel infoModel = categoryModel.sources[_secondaryIndex];
    /// 开始播放
    eventBus.fire(ChangePlaySourceEvent(infoModel));
  }

  /// 侧边栏是否隐藏
  void changeSlideStatus(bool isHidden){
    _isShowSlide = isHidden;
  }

  /// 手势点击修改侧边栏 index
  void gestureChangeSlideIndex(int categoryIndex, int secondaryIndex){
    _changeSlideSelected(categoryIndex, secondaryIndex);
    eventBus.fire(SlideChangeWithIndexEvent(categoryIndex,secondaryIndex));
    notifyListeners();
  }

  /// 修改选中的一级菜单
  void _changeSlideSelected(int categoryIndex,int secondaryIndex){
    _slideChooseIndex = secondaryIndex;
    _categoryIndex = categoryIndex;
    _secondaryIndex = secondaryIndex;
    /// 替换当前数据,重置选中状态
    _categorySources = _categorySources.map((e) {
      e.isChoose = false;
      return e;
    }).toList();
    var model = _categorySources[_categoryIndex];
    model.isChoose = true;
    model.sources = model.sources.map((e) {
      e.isChoose = false;
      return e;
    }).toList();
    model.sources[_secondaryIndex].isChoose = true;
    _categorySources[_categoryIndex] = model;
    eventBus.fire(ChangeSecondarySourceEvent(model));
  }

  /// 处理侧边栏弹出 左右按键事件
  void _changeCategoryStatus(int keyCode){
    _isChooseCategory = keyCode == KeyBoardCode.KEYCODE_DPAD_LEFT ;

    eventBus.fire(ChangeSourceMenuEvent(_isChooseCategory));
    //二级菜单刷新选中状态
    /// 替换当前数据,重置选中状态
    _categorySources = _categorySources.map((e) {
      e.isChoose = false;
      return e;
    }).toList();
    var model = _categorySources[_categoryIndex];
    model.isChoose = true;
    model.sources = model.sources.map((e) {
      e.isChoose = false;
      return e;
    }).toList();
    if(!_isChooseCategory){
      if(_currentCategoryModel.name == model.name){
        model.sources[_secondaryIndex].isChoose = true;
      }else{
        _slideChooseIndex = 0;
        model.sources[_slideChooseIndex].isChoose = true;
      }
    }

    _categorySources[_categoryIndex] = model;
    eventBus.fire(ChangeSecondarySourceEvent(model));
  }

  /// 重置数据状态
  void resetSourceStatus(){
    _categorySources = _categorySources.map((e) {
      e.isChoose = false;
      return e;
    }).toList();
    var model = _categorySources[_categoryIndex];
    model.isChoose = true;
    model.sources = model.sources.map((e) {
      e.isChoose = false;
      return e;
    }).toList();
    _categorySources[_categoryIndex] = model;
  }
}